﻿using System;
using System.Collections.Generic;
using System.Linq;
using VideoSeller.Business.Data;
using VideoSeller.Core.Interfaces;

namespace VideoSeller.Business.Models
{
	public class BonusFinanceModel : Repository<BonusFinance>
	{

        public decimal GetMany(Guid clientId, decimal summany)
        {
            decimal sum = 0;
            
            //if (client.BonusFinances == null || client.BonusFinances.Count == 0)
             //   return sum;
            IEnumerable<BonusFinance> bonus = GetAll().Where(m=>m.UserId == clientId && m.Total > 0);
            decimal before = bonus.Sum(m => m.Total);
            if (before == 0)
                return 0;
            try
            {
                foreach (BonusFinance c in bonus)
                {
                        sum += c.Total;
                        if (sum >= summany)
                        {
                            c.Total = Math.Abs(sum - summany);
                            c.InsDate = DateTime.Now;
                            sum = summany;
                            break;
                            
                        }
                        c.Total =0;
                }
                SubmitAllChanges();
            }
            catch
            {
                sum = 0;
            }
            if (sum > 0)
            {
                try
                {
                    decimal after = GetAll().Where(m => m.UserId == clientId && m.Total > 0).Sum(m=>m.Total) ;
                    if (!(before == sum && after == 0) && !((before - after) == summany))
                        sum = 0;
                }
                catch
                {
                    sum = 0;
                }
            }

            return sum;
        }
        
        public bool CheckEmail(String email, string ipAddr)
        {
            bool ret = Table.Where(m => m.NEMail.ToUpper() == email.ToUpper()).Count() > 0;
            if (!ret)
                ret = Table.Where(m => m.ipAddr.ToUpper() == ipAddr.ToUpper()).Count() > 0;
            return ret;
        }
        public decimal AddBonus(Client fromClient, Client toClient, decimal total, string ipAddr)
        {
            if (CheckEmail(fromClient.Email, ipAddr))
                return 0;
            BonusFinance b = new BonusFinance();
            b.NEMail = fromClient.Email;
            b.NUserID = fromClient.UserId;
            b.UserId = toClient.UserId;
            b.Total = total;
            b.InsDate = DateTime.Now;
            b.ipAddr = ipAddr;
            Insert(b);
            return toClient.BonusFinances.Sum(m => m.Total);

        }

	}
}